#include "videoRead.h"
#include "spdlog/spdlog.h"

using namespace std;
using namespace cv;

VideoRead::VideoRead() {
}

VideoRead::VideoRead(const std::string& videoPath) {
    open(videoPath);
}

VideoRead::~VideoRead() {}

void VideoRead::open(const std::string& videoPath) {
    cap_.open(videoPath);
    if (!cap_.isOpened()) {
        SPDLOG_ERROR("failed to open {}", videoPath);
        exit(1);
    }
    SPDLOG_INFO("open {} success", videoPath);
    fps_ = cap_.get(CAP_PROP_FPS);              // 帧率
    width_ = cap_.get(CAP_PROP_FRAME_WIDTH);    // 获取宽度
    height_ = cap_.get(CAP_PROP_FRAME_HEIGHT);  // 获取高度
    SPDLOG_INFO("height = {},width = {}", height_, width_);
    if (strncmp("rtsp", videoPath.c_str(), 4) == 0) {
        stayTime_ = 1;
    } else {
        stayTime_ = 1000 / fps_;
    }
}

void VideoRead::play() {
    isStop_ = false;
    if (playTh_) {
        return;
    }
    playTh_ = new thread([this]() {
        while (!isStop_) {
            Mat frame;
            cap_ >> frame;
            frameQue_.Push(frame);
            this_thread::sleep_for(std::chrono::milliseconds(stayTime_));
        }
    });
}

void VideoRead::stop() {
    if (!isStop_) {
        isStop_ = true;
        playTh_->join();
        delete playTh_;
        playTh_ = nullptr;
    }
}